import { message, getCurrCityArrByCity } from '@/utils/util';
import { get, save, update } from '@/views/script-settings/components/EditModal/api';
import { INITIAL_FORM_QUERY_VALUE } from '@/views/script-settings/constants';
import { parseToObject } from '@/utils';

export default {
  name: 'script-settings-edit-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    scriptFormValueString: {
      id: String,
      default: null,
    },
    // 省市
    cityList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      formValue: { id: null, city: undefined },
      onSubmitIng: false,
      formLabelWidth: '110px',
      rules: {
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        scriptType: [{ required: true, message: '请输入脚本类型', trigger: 'blur' }],
        scriptText: [{ required: true, message: '请输入脚本内容', trigger: 'blur' }],
      },
    };
  },
  watch: {
    scriptFormValueString(newValue) {
      if (!newValue) {
        return;
      }
      this.formValue = {
        ...this.formValue,
        ...parseToObject(newValue),
      };
      if (this.formValue.id) {
        this.onQuery(this.formValue.id);
      }
    },
  },
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            this.onSubmitIng = true;
            const params = {
              ...this.formValue,
              city: this.formValue.city && this.formValue.city.length > 0 ? this.formValue.city[this.formValue.city.length - 1] : undefined,
            };
            if (this.formValue.id) {
              await update(params);
            } else {
              await save(params);
            }
            this.onClose();
            this.resetTable();
            message('提示', '操作成功', 'success');
          } catch (e) {
            message('错误', e.message, 'error');
          }
          this.onSubmitIng = false;
        }
      });
    },
    onClose() {
      this.formValue = { ...INITIAL_FORM_QUERY_VALUE };
      this.$refs.formRef.resetFields();
      this.$emit('close');
    },
    resetTable() {
      this.$emit('resetTable');
    },
    async onQuery(id) {
      const result = await get(id);
      if (result) {
        this.formValue = {
          id: result.id,
          city: getCurrCityArrByCity(this.cityList, result.city),
          scriptType: result.scriptType,
          scriptText: result.scriptText,
        };
      }
    },
  },
  mounted() {},
};
